# 解析主程序名称
NUL 		:=
UNDER 	:= _
SPACE 	:= $(NUL) # 构造内容是一个空格的串
MKPATH 	:= $(abspath $(firstword $(MAKEFILE_LIST)))
CUR_DIR := $(notdir $(patsubst %/,%,$(dir $(MKPATH))))
CODE		:= $(firstword $(subst $(UNDER),$(SPACE),$(CUR_DIR)))$(UNDER)
PRG     := $(patsubst $(CODE)%,%,$(CUR_DIR))

# 源码、输入数据、预期答案
CPPS 		:= $(sort $(wildcard *.cpp))
INPUTS 	:= $(sort $(wildcard *.in))
ANSWERS := $(sort $(wildcard *.ans))

# 程序、临时输出
ELFS 		:= $(patsubst %.cpp,%.elf,$(CPPS))
TMPS 		:= $(patsubst %.ans,%.tmp,$(ANSWERS))

# 编译和链接参数
## 2级优化、全部普通警告、额外警告、非标警告、变量屏蔽警告
BFLAGS  	= -O2 -Wall -Wextra -Wpedantic -Wshadow -I../../tools/
CFLAGS 	 	= -std=c17 $(BFLAGS)
CXXFLAGS 	= -std=c++17 $(BFLAGS) -Weffc++
LDFLAGS 	= -lm

# 简化输出（除非定义VERBOSE变量）
ifneq ($(VERBOSE),1)
QCC 			= @echo '  cc    '$<;
QCXX 			= @echo '  c++   '$<;
QTEST			= @echo '  test  '$<;
QRM 			= @echo '  '$@;
endif

all: $(ELFS)

%.elf: %.c
	$(QCC) $(CC) $(CFLAGS) $^ $(LDFLAGS) -o $@

%.elf: %.cpp
	$(QCXX) $(CXX) $(CXXFLAGS) $^ $(LDFLAGS) -o $@

# 输出文件用.tmp是为避开编译输出a.out和OJ答案文件的扩展名要求。
%.tmp: %.in %.ans $(PRG).elf
	$(QTEST) ./$(PRG).elf < $*.in > $*.tmp && diff $*.ans $*.tmp

# 伪目标
.PHONY: clean cleanout data dump pta rebuild retest test

# 清理程序和临时文件
clean:
	$(QRM) rm -f *.tmp *.elf

# 清理临时文件
cleanout:
	$(QRM) rm -f *.tmp

data: gen_test.elf
	./gen_test.elf

dump:
	@echo $(PRG)
	@echo $(CPPS)
	@echo $(ELFS)
	@echo $(INPUTS)
	@echo $(ANSWERS)
	@echo $(TMPS)

# 按照PTA平台要求对测试集打包
pta:
	rm -f *.zip
	find . -type f -name '*.ans' -exec sh -c 'cp "{}" "$$(basename "{}" .ans).out"' \;
	zip -r $(PRG)_test.zip scores.txt *_test_*.in *_test_*.out
	rm -f *.out

# 重新构建程序
rebuild: clean all

# 重新测试
retest: cleanout test

# 测试
test: all $(TMPS)
